<!--
* 功能-页面实现
* Date: 2023-7-22
* Author: 靳从毅
 -->
 <template>
  <layout-card v-model="search" :filters="isaskOptions" headline="信息列表" headtitle="数据筛选" :hasButton="true"
    @search-change="searchChange" @search-reset="searchReset">
    <template #action>
      <el-button :disabled="isDisabled" type="primary" @click="handleExport">导出</el-button>
    </template>
    <table-common @sort-change="handleSort" stripe :columns="askColumns" :loading="loading" :pagination="pager"
      :table-data="tableData" size="large" @current-change="currentChange" @size-change="sizeChange">
    </table-common>
  </layout-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount, computed } from 'vue'
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import { askColumns } from '@/views/pax/ask/config/columns'
import { askOptions } from '@/views/pax/ask/config/filters'
import { askPageList, asklist, exportlist } from '@/api/pax/ask'
import { getResource } from '@/api/resource'
import type { PageListType } from '@/api/pax/ask'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const isaskOptions = ref(askOptions)

/**
 * 约束
 */
interface SearchType {
  askTimeStart?: string[]
  askTimeEnd?: string[]
  askType?: string
  askContent?: string
  askTime?: string
  recorder?: string
  askRegion?: string
  order?: any
}
interface ProblemType {
  askId?: number
  label?: string
  askContent?: string
  askTime: string
  id: number
  askType?: string
  recorder?: string
  recordTime?: string
  syncTime?: string
}

const loading = ref(false)
const tableData = ref<ProblemType[]>([])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 1
})

const search = ref<SearchType>({})

// 导出按钮禁用
const isDisabled = computed(() => {
  return tableData.value.length === 0
})

/**
 * 向api传参，进行条件查询
 */
/**
  * 功能-获取数据、分页查询
  * Date: 2023-7-24
  * Author: 郑清懋、王泽同
  */
const getData = async () => {
  loading.value = true
  const payload: PageListType = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {

    }
  }
  // 传递询问时间的查询条件到api
  if (search.value.askTime && search.value.askTime?.length > 0) {
    payload.askTimeStart = search.value.askTime[0] || ''
    payload.askTimeEnd =search.value.askTime[1] || ''}

  // 传递查询的内容到api
  if (search.value.askContent) {
    payload.askContent = search.value.askContent || ''
  }

  // 传递查询的记录人到api
  if (search.value.recorder) {
    payload.recorder = search.value.recorder || ''
  }
  if (search.value.order) {
    payload.order = search.value.order || ''
  }

  // 传递查询的类型到api
  if (search.value.askType && search.value.askType.length > 0) {
  if(search.value.askRegion === isaskOptions.value[0].inputProps.options[0].value){
    const askTypes = []
    isaskOptions.value[0].inputProps.options[0].children.forEach(item =>{
      search.value.askType.forEach(i => {
        if(item.value === i){
          askTypes.push(item.label)
        }
        payload.type = askTypes || ''
      });
    })
  }else{
    const askTypes = []
    isaskOptions.value[0].inputProps.options[1].children.forEach(item =>{
      search.value.askType.forEach(i => {
        if(item.value === i){
          askTypes.push(item.label)
        }
        payload.type = askTypes || ''
      });
    })
  }
}

  
  /**
   * 获取数据
   */
  // res获取查询后的数据列表
  const res = await askPageList(payload)
  // res2未加查询条件的数据列
  const res2 = await asklist(payload)

  // 获取数据列表，无法获取转圈圈
  loading.value = false
  if (res && res2) {
    tableData.value = res.data.list
    pager.total = res.data.total
    if(pager.total === 0){
      pager.pageCount = 1
    }else{
      pager.pageCount = Math.ceil(pager.total / pager.pageSize)
    } 
  } else {
    ElMessage.error('获取列表失败，请刷新重试！')
  }
}

/**
  * 功能-导出数据
  * Date: 2023-7-24
  * Author: 刘润
  * @param nowTime -导出表格的时间
  */
// 导出
const handleExport = () => {
  const payload: PageListType = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {

    }
  }
  // 传递询问时间的查询条件到api
  if (search.value.askTime && search.value.askTime?.length > 0) {
    payload.askTimeStart = search.value.askTime[0] || ''
    payload.askTimeEnd =search.value.askTime[1] || ''}

  // 传递查询的内容到api
  if (search.value.askContent) {
    payload.askContent = search.value.askContent || ''
  }

  // 传递查询的记录人到api
  if (search.value.recorder) {
    payload.recorder = search.value.recorder || ''
  }
  if (search.value.order) {
    payload.order = search.value.order || ''
  }

  search.value.askTime = undefined

  // 传递查询的类型到api
  if (search.value.askType && search.value.askType.length > 0) {
  if(search.value.askRegion === isaskOptions.value[0].inputProps.options[0].value){
    const askTypes = []
    isaskOptions.value[0].inputProps.options[0].children.forEach(item =>{
      search.value.askType.forEach(i => {
        if(item.value === i){
          askTypes.push(item.label)
        }
        payload.type = askTypes || ''
      });
    })
  }else{
    const askTypes = []
    isaskOptions.value[0].inputProps.options[1].children.forEach(item =>{
      search.value.askType.forEach(i => {
        if(item.value === i){
          askTypes.push(item.label)
        }
        payload.type = askTypes || ''
      });
    })
  }
}

  exportlist(payload)
    .then((res) => {
      const link = document.createElement('a')
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      const nowTime = dayjs().format('YYYYMMDD')
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute('download', `问询管理${nowTime}.xlsx`) // 报表名称可自定义
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
    .catch((res: any) => {
      ElMessage.error(res?.message || '导出失败')
    })
}

/**
  * 功能-排序查询
  * Date: 2023-7-24
  * Author: 刘润
  */
// 排序
const handleSort = (column: any) => {
  const prop = column.prop
  let order = column.order
  if (order === 'descending') {
    order = 'desc'
  } else if (order === 'ascending') {
    order = 'asc'
  }
  search.value.order = [{ column: prop, method: order }]
  getData()
}
//默认按照问询时间最新的排序
handleSort({order:"descending",prop:"askTime"})

/**
  * 功能-获取数据字典数据、渲染页面
  * Date: 2023-7-24
  * Author: 王泽同
  */
// 获取数据字典
const getArea = async () => {
  const res = getResource('pax_ask').then(
    (res) => {
      isaskOptions.value.forEach((e) => {
        if (e.prop === 'askRegion') {
          e.inputProps.options = res.data.properties.meta
        }
        e.events.change = function (value, evt) {
          evt.setFieldsValue({askType:null})
          
          if (value === 'pax_ask_region_01') {
            evt.setOptions('askType', res.data.properties.meta[0].children)
          } else {
            evt.setOptions('askType', res.data.properties.meta[1].children)
          }
        }
      })
    },
    (err) => {
      console.log(err)
    }
  )
}

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  getData()
}
const currentChange = (value: number) => {
  pager.currentPage = value
  getData()
}

/**
 * 点击查询
 */
const searchChange = (data: FilterDataType) => {
  search.value = data
  handleSort({order:"descending",prop:"askTime"})
  getData()
}

/**
 * 点击重置
 * @param data 数据
 */
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  handleSort({order:"descending",prop:"askTime"})
  getData()
}

onBeforeMount(() => {
  getData()
  getArea()
})
</script>

<style lang="less" scoped>

/deep/ .el-form-item__label {
      text-align: left;
      width: 85px !important;
      padding: 0;
      display: inline-block;
    }
</style>